package com.atguigu.gmall.activity.controller;

import com.atguigu.gmall.activity.service.SeckillGoodsService;
import com.atguigu.gmall.activity.util.CacheHelper;
import com.atguigu.gmall.common.constant.MqConst;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.result.ResultCodeEnum;
import com.atguigu.gmall.common.service.RabbitService;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.common.util.DateUtil;
import com.atguigu.gmall.model.activity.OrderRecode;
import com.atguigu.gmall.model.activity.SeckillGoods;
import com.atguigu.gmall.model.activity.UserRecode;
import com.atguigu.gmall.model.order.OrderDetail;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.model.user.UserAddress;
import com.atguigu.gmall.order.client.OrderFeignClient;
import com.atguigu.gmall.user.client.UserFeignClient;
import jodd.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@RestController
@RequestMapping("/api/activity/seckill")
public class SeckillGoodsApiController {

    @Autowired
    private SeckillGoodsService seckillGoodsService;

    @Autowired
    private RabbitService rabbitService;

    @Autowired
    private UserFeignClient userFeignClient;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private OrderFeignClient orderFeignClient;


    /**
     * 查询所有秒杀商品
     *
     * @return
     */
    @GetMapping("/findAll")
    public Result findAll() {
        return Result.ok(seckillGoodsService.seckillGoodList());
    }

    /**
     * 获取秒杀商品详情
     *
     * @param skuId
     * @return
     */
    @GetMapping("/getSeckillGoods/{skuId}")
    public Result getSeckillGoods(@PathVariable("skuId") Long skuId) {
        return Result.ok(seckillGoodsService.getSeckillGood(skuId));
    }


    /**
     * 获取下单码，防止非法抢购
     *
     * @param skuId
     * @param request
     * @return
     */
    @GetMapping("auth/getSeckillSkuIdStr/{skuId}")
    public Result getSeckillSkuIdStr(@PathVariable("skuId") Long skuId, HttpServletRequest request) {
//        获取用户id
        String userId = AuthContextHolder.getUserId(request);
        if (!StringUtil.isEmpty(userId)) {

//            查询秒杀商品信息
            SeckillGoods seckillGood = seckillGoodsService.getSeckillGood(skuId);
//            判断秒杀商品是否在时间范围内
            if (DateUtil.dateCompare(seckillGood.getStartTime(), new Date()) && DateUtil.dateCompare(new Date(), seckillGood.getEndTime())) {
//                在秒杀时间范围内，生成订单码
                String orderMd5 = DigestUtils.md5DigestAsHex(userId.getBytes());

                return Result.ok(orderMd5);
            }
        }

        return Result.fail().message("生成订单码失败");

    }

    /**
     * 根据用户和商品ID实现秒杀下单
     *
     * @param skuId
     * @return http://activity.gmall.com/seckill/queue.html?skuId=40&skuIdStr=c81e728d9d4c2f636f067f89cc14862c
     */
    @PostMapping("auth/seckillOrder/{skuId}")
    public Result seckillOrder(@PathVariable("skuId") Long skuId, HttpServletRequest request) throws Exception {

//        获取请求数据
        String skuIdStr = request.getParameter("skuIdStr");
        String userId = AuthContextHolder.getUserId(request);

//        获取产品标识， 1：可以秒杀 0：秒杀结束
        String state = (String) CacheHelper.get(skuId.toString());
//        判断下单是否合法
        if (StringUtil.isEmpty(state)) {
//            请求不合法
            return Result.build(null, ResultCodeEnum.SECKILL_ILLEGAL);
        } else if (!skuIdStr.equals(DigestUtils.md5DigestAsHex(userId.getBytes()))) {
//            请求不合法
            return Result.build(null, ResultCodeEnum.SECKILL_ILLEGAL);
        } else if (state.equals("0")) {
//            已售完
            return Result.build(null, ResultCodeEnum.SECKILL_FINISH);
        } else if (state.equals("1")) {

//      表识用户购买的商品信息
            UserRecode userRecode = new UserRecode();
            userRecode.setUserId(userId);
            userRecode.setSkuId(skuId);

//            下单成功，发送信息
            rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_SECKILL_USER,
                    MqConst.ROUTING_SECKILL_USER, userRecode);
        } else {
            return Result.build(null, ResultCodeEnum.SECKILL_ILLEGAL);
        }
        return Result.ok();
    }


    /**
     * 显示页面轮询接口
     *
     * @param skuId
     * @param request
     * @return
     */
    @GetMapping(value = "auth/checkOrder/{skuId}")
    public Result checkOrder(@PathVariable("skuId") Long skuId, HttpServletRequest request) {

//        获取用户id
        String userId = AuthContextHolder.getUserId(request);

        return seckillGoodsService.checkOrder(skuId, userId);
    }


    /**
     * 秒杀下单数据回显
     *
     * @param request
     * @return
     */
    @GetMapping("auth/trade")
    public Result trade(HttpServletRequest request) {
//        获取用户id
        String userId = AuthContextHolder.getUserId(request);
//        获取地址信息
        List<UserAddress> userAddresses =
                userFeignClient.findUserAddressListByUserId(userId);
//        查询订单详情信息
        OrderRecode orderRecode = (OrderRecode) redisTemplate.boundHashOps(RedisConst.SECKILL_ORDERS).get(userId);
//       存储订单集合
        List<OrderDetail> orderDetailList = new ArrayList<>();
        if (orderRecode != null) {
//            获取商品信息
            SeckillGoods seckillGoods = orderRecode.getSeckillGoods();
//            赋值数据
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setSkuId(seckillGoods.getSkuId());
            orderDetail.setSkuName(seckillGoods.getSkuName());
            orderDetail.setImgUrl(seckillGoods.getSkuDefaultImg());
            orderDetail.setSkuNum(orderRecode.getNum());
            orderDetail.setOrderPrice(seckillGoods.getCostPrice());

            orderDetailList.add(orderDetail);

//                计算商品总价格
            OrderInfo orderInfo = new OrderInfo();
            orderInfo.setOrderDetailList(orderDetailList);
            orderInfo.sumTotalAmount();

            Map<String, Object> result = new HashMap<>();
            result.put("userAddressList", userAddresses);
            result.put("detailArrayList", orderDetailList);
            // 保存总金额
            result.put("totalAmount", orderInfo.getTotalAmount());
            return Result.ok(result);

        } else {
            return Result.fail().message("下单失败");
        }

    }

    /**
     * 提交秒杀订单
     *
     * @param orderInfo
     * @param request
     * @return
     */
    @PostMapping("/auth/submitOrder")
    public Result submitOrder(@RequestBody OrderInfo orderInfo, HttpServletRequest request) {
//       获取用户id
        String userId = AuthContextHolder.getUserId(request);
        orderInfo.setUserId(Long.valueOf(userId));
//        保存秒杀订单数据
        Long orderId = orderFeignClient.submitOrder(orderInfo);
        if (orderId==null){
            return Result.fail().message("下单失败，请重新操作");
        }
//        删除redis中预下单数据
        redisTemplate.boundHashOps(RedisConst.SECKILL_ORDERS).delete(userId);
//        保存秒杀订单数据到redis中
        redisTemplate.boundHashOps(RedisConst.SECKILL_ORDERS_USERS).put(userId,orderId.toString());

        return Result.ok(orderId);
    }
}
